package com.john.booter.plugin.ueditor.impl;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State;
import com.john.booter.config.BooterSettings;
import com.john.booter.constant.StateType;
import com.john.booter.domain.entity.File;
import com.john.booter.module.file.service.FileService;
import com.john.booter.plugin.ueditor.StandardMultipartFile;
import com.john.booter.plugin.ueditor.UeditorService;

/**
 * UeditorService实现 - Common
 */
@Component("UeditorServiceCommonImpl")
public class UeditorServiceCommonImpl implements UeditorService{

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private BooterSettings setting; 
	
	@Autowired
	private FileService fileService;
	
	@Override
	public MultipartFile getMultipartFile(String filedName, HttpServletRequest request) {
		MultipartFile resultFile = null;
		try {
			MultipartHttpServletRequest multipartHttpservletRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartHttpservletRequest.getFile(filedName);
			if (!multipartFile.isEmpty()) {
				resultFile = new StandardMultipartFile(filedName, multipartFile.getInputStream(), multipartFile.getOriginalFilename(), multipartFile.getSize());
			}
		} catch (IOException e) {
			logger.error("文件上传失败，请检查配置参数是否正确！");
			e.printStackTrace();
		}
		return resultFile;
	}

	@Override
	public State saveFileByInputStream(MultipartFile file, long maxSize) throws IOException {
		State state = null;
		if (!file.isEmpty()) {
			String uuid = UUID.randomUUID().toString();
			
			byte[] bytes = file.getBytes();
			String baseUploadPath = setting.getFileUploadTempPath();
			String originalFilename = file.getOriginalFilename();
			String suffix = originalFilename.substring(originalFilename.lastIndexOf( "." ) ).toLowerCase();
			String relativePath = uuid + suffix;
			
			FileUtils.writeByteArrayToFile(new java.io.File(baseUploadPath + java.io.File.separator + relativePath), bytes);
			
			
			File f = new File();
			f.setId(uuid);
			f.setLocalPath(relativePath);
			f.setOriginName(originalFilename);
			f.setSaveName(uuid + suffix);
			f.setType(FilenameUtils.getExtension(originalFilename));
			f.setState(StateType.File.TEMP);
			// 把上传的文件信息记入数据库
			fileService.saveTemp(f);
			
			// 返回ueditor信息
			state = new BaseState(true);
			state.putInfo("size", file.getSize());
			state.putInfo("title", file.getOriginalFilename());
			state.putInfo("url", setting.getImageViewURL() + f.getSaveName());
			return state;
		} else {
			logger.error("文件上传失败，请检查配置参数是否正确！");
			return new BaseState(false, AppInfo.IO_ERROR);
		}

	}
	
	@Override
	public State saveBinaryFile(byte[] bytes, String fileName) {
		State state = null;
		if (ArrayUtils.isNotEmpty(bytes)) {
			String uuid = UUID.randomUUID().toString();
			
			String baseUploadPath = setting.getFileUploadTempPath();
			String suffix = FilenameUtils.getExtension(fileName);
			String relativePath = uuid + suffix;
			
			java.io.File file = new java.io.File(baseUploadPath + java.io.File.separator + relativePath);
			
			try {
				FileUtils.writeByteArrayToFile(file, bytes);
			} catch (IOException e) {
				logger.error("文件上传失败，请检查配置参数是否正确！", e);
				return new BaseState(false, AppInfo.IO_ERROR);
			}
			
			
			File f = new File();
			f.setId(uuid);
			f.setLocalPath(relativePath);
			f.setOriginName(fileName);
			f.setSaveName(uuid + suffix);
			f.setType(FilenameUtils.getExtension(fileName));
			f.setState(StateType.File.TEMP);
			// 把上传的文件信息记入数据库
			fileService.saveTemp(f);
			
			// 返回ueditor信息
			state = new BaseState(true);
			state.putInfo("size", FileUtils.sizeOf(file));
			state.putInfo("title", fileName);
			state.putInfo("url", setting.getImageViewURL() + f.getSaveName());
			return state;
		} else {
			logger.error("文件上传失败，请检查配置参数是否正确！");
			return new BaseState(false, AppInfo.IO_ERROR);
		}
	}
	
	@Override
	public State listFile(String[] allowFiles, int start, int pageSize) {
		// 把计入数据库中的文件信息读取出来，返回即可

		// 下面的代码，仅作示例
		State state = new MultiState(true);
		state.putInfo("start", start);
		state.putInfo("total", 0);
		return state;
	}
	
}